package com.hotel.wallet.controller;


import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.common.config.SystemConfig;
import com.hotel.common.util.JwtUtil;
import com.hotel.common.vo.R;
import com.hotel.user.entity.PayLog;
import com.hotel.user.entity.UserCashbackLog;
import com.hotel.wallet.mapper.PayLogMapper;
import com.hotel.wallet.mapper.UserCashbackLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhy
 * @since 2024-06-19
 */
@RestController
@RequestMapping("/user/wallet")
public class UserCashbackLogController {

    @Autowired
    private PayLogMapper payLogMapper;

    @Autowired
    private UserCashbackLogMapper userCashbackLogMapper;

    /**
     * 展示返现详情
     */
    @RequestMapping("/cashBackLog")
    public R findCashback(HttpServletRequest request) {

        // 获取id
        // 前端没有传id，通过token得到id需要HttpServletRequest
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        // 解析token得到id(token是由user.getId(), user.getAccount(), user.getPhone()组成)
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(token, "id")).intValue();

        // payLog中找到和token中id相同的用户,查找房费
        QueryWrapper<PayLog> payLogQueryWrapper = new QueryWrapper<>();
        payLogQueryWrapper.eq("user_id", id);

        List<PayLog> payLogList = payLogMapper.selectList(payLogQueryWrapper);

        UserCashbackLog userCashbackLog = new UserCashbackLog();

        // 遍历每一条数据，筛选出付款的订单金额
        for (PayLog payLog : payLogList) {
            if (payLog.getStatus() == 2 && payLog.getNo().startsWith("r")) {

                // 插入userCashback表数据

                // 设置userCashbackLog为此id的对象
                userCashbackLog.setUserId(id);
                userCashbackLog.setAmount(payLog.getMoney() * 0.1);
                // 返现订单号,
                // 时间戳+6位随机数
                String no = "fx" + System.currentTimeMillis() + RandomUtil.randomNumbers(6);
                userCashbackLog.setNo(no);
                userCashbackLog.setStatus(1);
                userCashbackLog.setCtime(new Date());

                userCashbackLogMapper.insert(userCashbackLog);

                }
        }
        return R.ok(userCashbackLog);
    }

}

